package com.chuanyang.driverh.mainorder;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.RecodeState;
import com.chuanyang.driverh.amap.MapUtils;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.adapter.OrderInfoAdapter;
import com.chuanyang.driverh.mainorder.adapter.OrderPassPointAdapter;
import com.chuanyang.driverh.mainother.BeforeNaviActivity;
import com.chuanyang.driverh.responseresult.CarCurrentStatusResult;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.OrderAddressResult;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.responseresult.ValidateCodeResult;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.TimeUtils;
import com.chuanyang.driverh.utils.eventbus.CloseOrderDetailEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshOrderData;
import com.chuanyang.driverh.utils.eventbus.SubscribeEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


public class NewOrderDetailActivity extends BaseTitleActivity {
    public int index = 0;
    private ImageView iv_peopleicon;
    private RatingBar ratingBar;
    private TextView tv_peoplename;
    private TextView tv_phone;
    private TextView tv_orderdate;
    private TextView tv_oredrinfo_deliverydate;
    private TextView tv_oredrinfo_picuupdate;
    private TextView tv_oredrinfodetail_orderid;
    private TextView tv_oredrinfo_act;
    private CustomMeasureHeightListView lv_varpalaces;
    private CustomMeasureHeightListView lv_orderlist;
    private ScrollView sc_orderdetail;
    private OrderDetailData.PassPointsBean startPoint;
    private OrderDetailData.PassPointsBean endPoint;
    private List<OrderDetailData.PassPointsBean> fillpointlist;
    private OrderPassPointAdapter passPointAdapter;
    private List<OrderDetailData.PassPointsBean> passpointlist;
    private LinearLayout ll_oredrinfo_goodownerdiv;
    private TextView tv_oredrinfo_dingyue;
    private String orderId;
    private OrderDetailData orderDetail;
    private LinearLayout ll_oredrinfo_act;
    private TextView tv_oredrinfo_act2;
    private TextView tv_oredrinfo_remark;
    private ImageView iv_oredrinfo_phoneicon;
    private DriverInfoData driverinfo;
    private EditText et_sureunload_code;
    private TextView tv_cancle_unload;
    private TextView tv_sureunload_getcode;
    private TextView tv_sure_unload;
    private boolean validateOk;
    private TextView tv_oredrinfodetail_realnum;
    private TextView tv_oredrinfodetail_orginnum;
    private TextView tv_oredrinfodetail_realweight;
    private TextView tv_oredrinfodetail_orginweight;
    private TextView tv_oredrinfodetail_realamount;
    private TextView tv_oredrinfodetail_orginamount;
    private TextView tv_oredrinfodetail_tradetype;
    private TextView tv_oredrinfodetail_taskname;
    private LinearLayout ll_orderinfo_cartimediv;
    private LinearLayout ll_orderinfo_shiptimediv;
    private TextView tv_driverinfo_loaddatebeg;
    private TextView tv_driverinfo_loaddateend;
    private TextView tv_driverinfo_stevedoreDaybeg;
    private TextView tv_driverinfo_stevedoreDayend;
    private TextView tv_oredrinfodetail_demurrage;
    private AlertDialog alertDialog;
    private Dialog dialog;

    @Override
    protected int getContentResId() {
        return R.layout.order_neworderdetailinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showActivityLoading();
        ll_oredrinfo_goodownerdiv = (LinearLayout) findViewById(R.id.ll_oredrinfo_goodownerdiv);
        sc_orderdetail = (ScrollView) findViewById(R.id.sc_orderdetail);
        iv_peopleicon = (ImageView) findViewById(R.id.iv_oredrinfo_peopleicon);
        ratingBar = (RatingBar) findViewById(R.id.rb_orderinfo_stars);
        tv_peoplename = (TextView) findViewById(R.id.tv_oredrinfo_peoplename);
        tv_oredrinfodetail_tradetype = (TextView) findViewById(R.id.tv_oredrinfodetail_tradetype);//订单外贸类型（1人民币，2美元）
        tv_oredrinfodetail_taskname = (TextView) findViewById(R.id.tv_oredrinfodetail_taskname);//任务名称 有则显示
        tv_oredrinfo_dingyue = (TextView) findViewById(R.id.tv_oredrinfo_dingyue);//订阅
        tv_phone = (TextView) findViewById(R.id.tv_oredrinfo_phone);
        iv_oredrinfo_phoneicon = (ImageView) findViewById(R.id.iv_oredrinfo_phoneicon);
        tv_orderdate = (TextView) findViewById(R.id.tv_oredrinfo_orderdate);//发单时间

        //车辆订单时显示的界面
        ll_orderinfo_cartimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_cartimediv);
        tv_oredrinfo_deliverydate = (TextView) findViewById(R.id.tv_oredrinfo_deliverydate);//发货时间
        tv_oredrinfo_picuupdate = (TextView) findViewById(R.id.tv_oredrinfo_picuupdate);//取货时间

        //-----------------------

        //船只订单时显示的界面
        ll_orderinfo_shiptimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_shiptimediv);
        tv_driverinfo_loaddatebeg = (TextView) findViewById(R.id.tv_driverinfo_loaddatebeg);
        tv_driverinfo_loaddateend = (TextView) findViewById(R.id.tv_driverinfo_loaddateend);
        tv_driverinfo_stevedoreDaybeg = (TextView) findViewById(R.id.tv_driverinfo_stevedoreDaybeg);
        tv_driverinfo_stevedoreDayend = (TextView) findViewById(R.id.tv_driverinfo_stevedoreDayend);
        //滞期费
        tv_oredrinfodetail_demurrage = (TextView) findViewById(R.id.tv_oredrinfodetail_demurrage);

        //-----------------------


        tv_oredrinfo_remark = (TextView) findViewById(R.id.tv_oredrinfo_remark);
        tv_oredrinfodetail_orderid = (TextView) findViewById(R.id.tv_oredrinfodetail_orderid);//订单号
        //实际数量
        tv_oredrinfodetail_realnum = (TextView) findViewById(R.id.tv_oredrinfodetail_realnum);
        //下单数量
        tv_oredrinfodetail_orginnum = (TextView) findViewById(R.id.tv_oredrinfodetail_orginnum);

        //实际载重
        tv_oredrinfodetail_realweight = (TextView) findViewById(R.id.tv_oredrinfodetail_realweight);
        //下单载重
        tv_oredrinfodetail_orginweight = (TextView) findViewById(R.id.tv_oredrinfodetail_orginweight);
        //实际金额
        tv_oredrinfodetail_realamount = (TextView) findViewById(R.id.tv_oredrinfodetail_realamount);
        //下单金额
        tv_oredrinfodetail_orginamount = (TextView) findViewById(R.id.tv_oredrinfodetail_orginamount);
        ll_oredrinfo_act = (LinearLayout) findViewById(R.id.ll_oredrinfo_act);        //底部两个按钮所在布局
        tv_oredrinfo_act = (TextView) findViewById(R.id.tv_oredrinfo_act);//最底部的按钮1
        tv_oredrinfo_act2 = (TextView) findViewById(R.id.tv_oredrinfo_act2);//最底部的按钮2
        lv_varpalaces = (CustomMeasureHeightListView) findViewById(R.id.ll_oredrinfo_varpalace);
        lv_orderlist = (CustomMeasureHeightListView) findViewById(R.id.ll_orderinfo_orderlist);


    }

    @Override
    protected void initData() {
        RecodeState.setOrderDetailOpenning(true);
        setBackImg();
        Intent intent = getIntent();
        getTitleTextView().setText("订单详情");
        orderId = intent.getStringExtra("data");
        driverinfo = BaseApplication.getInstance().getDriverInfo();

        if (driverinfo.getDriver() != null && driverinfo.getDriver().getCarId() != 0) {
            GetCarCurrentStatusByCarID(driverinfo.getDriver().getCarId() + "");
//           GetCarCurrentStatusByCarID(117917+"");
        } else {
            GetCarCurrentStatusByCarID("");
        }
    }

    @Override
    protected void initListener() {
        ll_oredrinfo_goodownerdiv.setOnClickListener(this);
        tv_oredrinfo_act.setOnClickListener(this);
        tv_oredrinfo_act2.setOnClickListener(this);
        iv_oredrinfo_phoneicon.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_oredrinfo_goodownerdiv:
                if (orderDetail != null) {
                    startActivity(GoodOwnerInfoActivity.class, orderDetail);
                }
                break;
            case R.id.tv_oredrinfo_act:
                if (orderDetail == null)return;
                    if (orderDetail.getOrder_status() == 1) {
                    startActivity(AssignGoodsActivity.class, orderDetail.getOrderId() + "");
                    finish();

                } else if (orderDetail.getOrder_status() == 2) {
                    if (orderDetail != null) {
                        startTranslate();
                    }


                } else if (orderDetail.getOrder_status() == 3) {
                    PrintUtil.toast(activityContext,"装货向导");

                } else if (orderDetail.getOrder_status() == 4) {
                    if (orderDetail != null) {
                        // startActivity(MarkerActivity.class, orderDetail);
                        selectOrderAddress(orderDetail.getOrderId() + "");
                    }

                } else if (orderDetail.getOrder_status() == 5) {
                    PrintUtil.toast(activityContext,"卸货向导");

                } else if (orderDetail.getOrder_status() == 6) {
                    sureAcceptGood();
                }

                break;
            case R.id.tv_oredrinfo_act2:
                if (orderDetail == null)return;
                Intent intent = new Intent(NewOrderDetailActivity.this, SureUnLoadOverActivity.class);
                intent.putExtra("orederId", orderDetail.getOrderId());
                if(orderDetail.getFleetId()==0)
                {
                    intent.putExtra("personalOrder", true);

                }
                startActivity(intent);
                finish();
                break;
            case R.id.iv_oredrinfo_phoneicon:
                if (orderDetail != null && orderDetail.getPhone() != null) {
                    dial(orderDetail.getPhone());

//                    MyDialog.showTellDialog(this, handler, orderDetail.getPhone(), 2);
                }
                break;
        }
    }
    private void dial(final String tel){
        dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定","确定拨打："+tel+"?", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        DialogUtil.dial(activityContext,tel);
                      /*  Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
                        try {
                            if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                                startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }*/
                        break;
                }
                dialog.cancel();
            }
        });
    }

    /**
     * 开始运输
     */
    private void startTranslate() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", orderDetail.getWaybillSimpleMsg().getWaybillId() + "");
        params.put("waybillStatus", "4");
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.startTranslate(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    ll_oredrinfo_act.setVisibility(View.VISIBLE);
                    if (orderDetail.getTransPortWay() == 1)//车
                    {
                        tv_oredrinfo_act.setText("导航");
                    } else if (orderDetail.getTransPortWay() == 2) {
                        tv_oredrinfo_act.setVisibility(View.GONE);
                    }
                    tv_oredrinfo_act2.setText("运输完成");
                    tv_oredrinfo_act2.setVisibility(View.VISIBLE);
                    orderDetail.setOrder_status(4);
                    EventBus.getDefault().post(new RefleshOrderData(1));
                }else {
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }

    /**
     * 通过订单车辆位置
     * CarID
     *
     * @param
     */
    private void GetCarCurrentStatusByCarID(String carId) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("CarID", carId + "");
        MyHttpUtil.GetCarCurrentStatusByCarID(activityContext,params, new MyCallback<CarCurrentStatusResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
//                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                requsetData();
            }
            @Override
            public void onSuccess(CarCurrentStatusResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    if (result.getData() != null && result.getData().size() > 0) {
                        LatLng targetLatLng= MapUtils.getGdLatLng(NewOrderDetailActivity.this,result.getData().get(0).getLast_lat() ,result.getData().get(0).getLast_lon());
                        SharedPrefUtil.setTargetLat(targetLatLng.latitude+ "");
                        SharedPrefUtil.setTargetLog(targetLatLng.longitude+"");
                    }
                }
                requsetData();
            }
        });

    }

    private void requsetData() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);
        MyHttpUtil.selectOrderMsgById(activityContext,params, new MyCallback<OrderDatailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    orderDetail = result.getData();
                    fillView(orderDetail);
                    hideActivityLoading();
                }
            }
        });

    }

    private void selectOrderAddress(String id) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", id);
        MyHttpUtil.selectOrderAddress(activityContext,params, new MyCallback<OrderAddressResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderAddressResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    Intent intent = new Intent(NewOrderDetailActivity.this, BeforeNaviActivity.class);
                    intent.putExtra("OrderAddressResult", result);
                    startActivity(intent);
                    finish();
                }else {
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });





    }

    /**
     * 卸货完成 （传入订单id或者运单id）
     */
    private void updateWaybillUnload(final Integer id) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", id+"");
        params.put("waybillStatus", "6");
        MyHttpUtil.updateWaybillUnload(activityContext,params, new MyCallback<OrderAddressResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderAddressResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    Intent intent = new Intent(NewOrderDetailActivity.this, UnLoadOverGoodsActivity.class);
                    intent.putExtra("orederId", id);
                    startActivity(intent);
                    finish();
                }else {
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }



    /**
     * 如果订阅信息有变化时，需要修改其订阅按钮的状态
     *
     * @param event
     */
    public void onEventMainThread(SubscribeEvent event) {
        if (event.isChangeSubscribed()) {
            requsetData();
        }

    }

    /**
     * 关闭当前页面
     *
     * @param event
     */
    public void onEventMainThread(CloseOrderDetailEvent event) {
        if (event.isFinish()) {
            finish();
        }

    }

    private void fillView(OrderDetailData data) {
        tv_oredrinfodetail_orderid.setText(data.getOrderNo());
        BitmapUtil.showImgForNetPath(data.getUserImage(),iv_peopleicon);
//        YncApplication.getInstance().loadCircleImage(NewOrderDetailActivity.this, data.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, iv_peopleicon);
        if (data.getStar() != 0) {
            ratingBar.setRating(data.getStar());
        }
        if(!TextUtils.isEmpty(data.getAssignment()))
        {
            tv_oredrinfodetail_taskname.setText("任务名称："+data.getAssignment());
        }
        else {
            tv_oredrinfodetail_taskname.setVisibility(View.GONE);
        }
        if(data.getCurrency()==1)
        {
            tv_oredrinfodetail_tradetype.setVisibility(View.GONE);
        }
        else {
            tv_oredrinfodetail_tradetype.setVisibility(View.VISIBLE);

        }
        tv_phone.setText(data.getPhone());
        if (!TextUtils.isEmpty(data.getRemark())) {
            tv_oredrinfo_remark.setText(data.getRemark());
        } else {
            tv_oredrinfo_remark.setText(" ");

        }
        if (data.getUsername() != null) {
            tv_peoplename.setText(data.getUsername());

        } else {
            tv_peoplename.setText("---");

        }
        if (data.getSubscriptionStatus() == 1) {
            tv_oredrinfo_dingyue.setText("已订阅");
        } else if (data.getSubscriptionStatus() == 2) {
            tv_oredrinfo_dingyue.setText("未订阅");
        }
        if (data.getTransPortWay() == 1)//车
        {
            tv_oredrinfo_deliverydate.setText(TimeUtils.getStandardTime(data.getOrder_startime()));
            tv_oredrinfo_picuupdate.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            ll_orderinfo_cartimediv.setVisibility(View.VISIBLE);
            ll_orderinfo_shiptimediv.setVisibility(View.GONE);

        } else if (data.getTransPortWay() == 2)//船
        {
            tv_driverinfo_loaddatebeg.setText(data.getLoadDate());
            tv_driverinfo_loaddateend.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            tv_driverinfo_stevedoreDaybeg.setText(data.getStevedoreDay());
            tv_driverinfo_stevedoreDayend.setText(data.getFq());
            tv_oredrinfodetail_demurrage.setText(data.getDemurrage()+data.getUnit()+"/天/吨");
            ll_orderinfo_cartimediv.setVisibility(View.GONE);
            ll_orderinfo_shiptimediv.setVisibility(View.VISIBLE);

        }

        tv_orderdate.setText(TimeUtils.getStandardTime(data.getOrder_time()));
        passpointlist = new ArrayList();
        //需要传入到适配器的数据
        fillpointlist = new ArrayList();
        for (OrderDetailData.PassPointsBean passPointsBean : data.getPassPoints()) {
            if (passPointsBean.getPointType().equals("s")) {
                startPoint = passPointsBean;
            } else if (passPointsBean.getPointType().equals("p")) {
                passpointlist.add(passPointsBean);
            } else {
                endPoint = passPointsBean;

            }
        }
        OrderInfoAdapter orderInfoAdapter = new OrderInfoAdapter(this, data.getDetailList());
        lv_orderlist.setAdapter(orderInfoAdapter);
        fillpointlist.clear();
        fillpointlist.add(startPoint);
        lv_varpalaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (passpointlist.size() > 0) {
                    if (0 < position && position < passpointlist.size() + 1) {
                        fillpointlist.clear();
                        fillpointlist.add(startPoint);
                        if ((index++) % 2 == 1) {
                            fillpointlist.addAll(passpointlist);
                            fillpointlist.add(endPoint);

                        } else {
                            fillpointlist.add(passpointlist.get(0));
                            fillpointlist.add(endPoint);

                        }

                        passPointAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        if (passpointlist.size() > 0) {
            fillpointlist.add(passpointlist.get(0));


        }
        fillpointlist.add(endPoint);
        passPointAdapter = new OrderPassPointAdapter(this, fillpointlist);
        //设置数据适配器
        lv_varpalaces.setAdapter(passPointAdapter);
        if (orderDetail.getGoodsSum() != null) {
            tv_oredrinfodetail_orginweight.setText("下单重量："+orderDetail.getGoodsSumWeight()+"t");
            tv_oredrinfodetail_orginnum.setText("下单数量："+orderDetail.getGoodsSumNum());
            double orginamount = (orderDetail.getGoodsSum().getGoodsWeight()) * (orderDetail.getPrice());
            tv_oredrinfodetail_orginamount.setText("下单金额："+String.format("%.2f", orginamount) + orderDetail.getUnit());
        }
        else {
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);

        }

        if(orderDetail.getRealitySum()!=null)
        {
            tv_oredrinfodetail_realnum.setText("实际数量："+orderDetail.getRealitySum().getRealityNum());
            tv_oredrinfodetail_realweight.setText("实际重量："+orderDetail.getRealitySum().getRealityWeight()+"t");
            double realamount=(orderDetail.getRealitySum().getRealityWeight())*orderDetail.getPrice();
            tv_oredrinfodetail_realamount.setText("实际金额："+String.format("%.2f", realamount)+data.getUnit());
        }
        else {
            tv_oredrinfodetail_realnum.setVisibility(View.GONE);
            tv_oredrinfodetail_realweight.setVisibility(View.GONE);
            tv_oredrinfodetail_realamount.setVisibility(View.GONE);
        }
        if (orderDetail.getOrder_status() < 0) {

            ll_oredrinfo_act.setVisibility(View.GONE);

        }
        if (orderDetail.getOrder_status() == 0) {//刚刚初始化的订单

            ll_oredrinfo_act.setVisibility(View.GONE);

        }
        if (orderDetail.getOrder_status() == 1) {
            tv_oredrinfo_act2.setVisibility(View.GONE);
            tv_oredrinfo_act.setText("部署");

        } else if (orderDetail.getOrder_status() == 2) {

            if (orderDetail.getFleetId() != 0) {
                ll_oredrinfo_act.setVisibility(View.GONE);

            } else {
                tv_oredrinfo_act.setText("开始运输");
                tv_oredrinfo_act2.setVisibility(View.GONE);

            }

        } else if (orderDetail.getOrder_status() == 3) {

            if (orderDetail.getFleetId() != 0) {
                ll_oredrinfo_act.setVisibility(View.GONE);

            } else {
                tv_oredrinfo_act.setText("装货向导");
                tv_oredrinfo_act2.setVisibility(View.GONE);


            }

        } else if (orderDetail.getOrder_status() == 4) {

            if (orderDetail.getFleetId() != 0) {
                ll_oredrinfo_act.setVisibility(View.GONE);

            } else //此时为个人订单
            {

//                if (showUnload(endPoint.getLongitude(), endPoint.getLatitude())) {

                if (data.getTransPortWay() == 1)//车
                {
                    tv_oredrinfo_act.setText("导航");
                } else if (data.getTransPortWay() == 2) {
                    tv_oredrinfo_act.setVisibility(View.GONE);
                }

                tv_oredrinfo_act2.setText("运输完成");
//                } else {
//                    tv_oredrinfo_act2.setVisibility(View.GONE);
//                    tv_oredrinfo_act.setText("导航");
//
//
//                }
            }


        } else if (orderDetail.getOrder_status() == 5) {
            //  if (showUnload(endPoint.getLatitude(), endPoint.getLongitude())) {
            if (orderDetail.getFleetId() != 0) {
                ll_oredrinfo_act.setVisibility(View.GONE);

            } else //此时为个人订单
            {
                tv_oredrinfo_act.setText("卸货向导");
                tv_oredrinfo_act2.setText("运输完成");
            }


        } else if (orderDetail.getOrder_status() == 6) {
            //  ll_oredrinfo_act.setVisibility(View.GONE);
            if (orderDetail.getFleetId() != 0) {
                ll_oredrinfo_act.setVisibility(View.GONE);

            } else //此时为个人订单
            {
                tv_oredrinfo_act2.setVisibility(View.GONE);
                tv_oredrinfo_act.setText("验证卸货");
            }

        }
        else if(orderDetail.getOrder_status()==7)
        {
            ll_oredrinfo_act.setVisibility(View.GONE);
        }


        //滚动到原点  注意这两个方法需要一起使用 前者打断动画，后者实现移动
        sc_orderdetail.scrollTo(0, 0);
        sc_orderdetail.smoothScrollTo(0, 0);
    }
    /**
     * 是否显示确认卸货按钮（此处通过判断距离目的地距离，25公里之内则显示，否则不显示）
     *
     * @return
     */
    public boolean showUnload(String lat, String Lng) {
        String lngCurrentStr = SharedPrefUtil.getTargetLog();
        String latCurrentStr = SharedPrefUtil.getTargetLat();

        if (TextUtils.isEmpty(lngCurrentStr) || TextUtils.isEmpty(latCurrentStr)) {
            return false;

        }
        double lngCurrent = Double.parseDouble(lngCurrentStr);
        double latCurrent = Double.parseDouble(latCurrentStr);
        double lngTarget = Double.parseDouble(Lng);
        double latTarget = Double.parseDouble(lat);
        LatLng latlngCurrent = new LatLng(latCurrent, lngCurrent);
        LatLng latlngTarget = new LatLng(latTarget, lngTarget);
        float distance = AMapUtils.calculateLineDistance(latlngCurrent, latlngTarget);
        if (distance < 2500 * 1000) {
            return true;
        }

        return false;
    }

    /**
     * 提示司机输入收货人验证码
     *
     */
    public void sureAcceptGood() {
        if (null == alertDialog) {
            alertDialog = new AlertDialog.Builder(NewOrderDetailActivity.this).create();
            alertDialog.show();
            alertDialog.setTitle(null);
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    alertDialog = null;
                }
            });
            Window window = alertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawable(new ColorDrawable(0));
            window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setContentView(R.layout.dialog_sureunload);
            View view = window.getDecorView();
            et_sureunload_code = (EditText) view.findViewById(R.id.et_sureunload_code);
            tv_cancle_unload = (TextView) view.findViewById(R.id.tv_cancle_unload);
            tv_sureunload_getcode = (TextView) view.findViewById(R.id.tv_sureunload_getcode);
            tv_sure_unload = (TextView) view.findViewById(R.id.tv_sure_unload);
            tv_cancle_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });

            tv_sureunload_getcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!validateOk) {//获取成功验证码 且对话框没消失时无法多次点击
                        getValidateCode();
                    }
                    else {
                        PrintUtil.toast(activityContext,"验证码已发送给货主！");
                    }
                }
            });
            tv_sure_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    if (TextUtils.isEmpty(et_sureunload_code.getText().toString().trim())) {
                        PrintUtil.toast(activityContext,"请填写获取到验证码");
                        return;
                    }
                    if (!validateOk){
                        PrintUtil.toast(activityContext,"请先获取验证码");
                        return;
                    }


                    if(orderDetail.getFleetId()!=0) {
                        updateWaybillUnload();
                    }
                    else {
                        updateOrderUnload();
                    }

                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
        }
        //下面两行代码加入后即可弹出输入法
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    private void getValidateCode() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("phone", endPoint.getContactPhone());
        params.put("validateMsg", orderId);
        MyHttpUtil.getSureValidateCode(activityContext,params, new MyCallback<ValidateCodeResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ValidateCodeResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    validateOk = true;
                    tv_sureunload_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.tv_shape_gray_round_corner_solid));
                }else {
                    PrintUtil.toast(activityContext,"获取验证码失败");
                }
            }
        });



    }
    /**
     * 代替货主收货接口 (个人订单时)  和上面的接口一致
     */
    private void updateOrderUnload() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("orderStatus", "7");
        params.put("validateMsg", orderId);
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        ArrayList<File> files=new ArrayList();
        MyHttpUtil.updateOrderUnload(activityContext,files, params,new MyCallback<ValidateCodeResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ValidateCodeResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    PrintUtil.toast(activityContext,"您已替货主确认收货");
                    EventBus.getDefault().post(new RefleshOrderData(1));
                    finish();
                }else {
                    PrintUtil.toast(activityContext,"替货主确认收货失败!");
                }
            }
        });
    }
    /**
     * 收货完成 （传入订单id或者运单id）
     */
    private void updateWaybillUnload() {

        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("waybillStatus", "7");
        params.put("validateMsg", orderId);
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.updateWaybillStatus(activityContext, params,new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    PrintUtil.toast(activityContext,"您已替货主确认收货");
                    EventBus.getDefault().post(new RefleshOrderData(1));
                    finish();
                }else {
                    PrintUtil.toast(activityContext,"替货主确认收货失败!");
                }
            }
        });

    }
}
